package org.shilong.Loader;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;

/**
 * @author cesc
 * 
 */
public class ImageLoader {

	private final Handler handler = new Handler();

	/* Hashmap缓存 */
	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

	/* 线程池 */
	private ExecutorService executorService = Executors.newFixedThreadPool(5);

	/**
	 * 读取图片
	 * 
	 * @param imageUrl
	 * @param callback
	 * @return
	 */
	public Drawable loadImage(final String imageUrl,
			final ImageCallBack callback) {

		if (imageCache.containsKey(imageUrl)) {

			SoftReference<Drawable> soft = imageCache.get(imageUrl);

			if (soft.get() != null) {
				System.out.println("缓存中这个图片加入进去！！");
				return soft.get();
			}
		}

		executorService.submit(new Runnable() {

			@Override
			public void run() {

				final Drawable drawable = loadedImageFromUrl(imageUrl);

				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				System.out.println("将图片加入缓存中....");
				handler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

						callback.setImageDrawable(drawable);
					}
				});

			}
		});

		return null;
	}

	/**
	 * 下载图片
	 * 
	 * @param url
	 * @return
	 */
	private Drawable loadedImageFromUrl(String url) {

		Drawable drawable = null;
		try {
			drawable = Drawable.createFromStream(new URL(url).openStream(),
					"image.jpg");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return drawable;
	}

	public interface ImageCallBack {

		public void setImageDrawable(Drawable imageDrawable);
	}

	/**
	 * 图片异步下载类
	 * 
	 * @author Administrator
	 * 
	 */
	/*
	 * private class DownloadTask extends AsyncTask<String, String, Drawable>{
	 * 
	 * @Override protected Drawable doInBackground(String... params) { // TODO
	 * Auto-generated method stub Drawable dd = null; try { dd =
	 * Drawable.createFromStream(new URL(params[0]).openStream(),"image.jpg"); }
	 * catch (MalformedURLException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated
	 * catch block e.printStackTrace(); }
	 * 
	 * return dd; }
	 * 
	 * @Override protected void onPostExecute(Drawable result) { // TODO
	 * Auto-generated method stub drawable = result; }
	 * 
	 * 
	 * }
	 */

}
